<template>
  <el-dialog
    v-model="visible"
    :before-close="close"
    :title="$t('product.select')"
    top="100px"
    :append-to-body="visible"
    :close-on-click-modal="false"
    width="60%"
  >
    <el-form
      :inline="true"
      :model="dataForm"
      class="demo-form-inline"
      @submit.prevent
    >
      <el-form-item :label="$t('product.prodName')">
        <el-input
          v-model="prodName"
          :placeholder="$t('product.prodName')"
          clearable
        />
      </el-form-item>
      <el-form-item :label="$t('coupon.categoryParent')">
        <el-cascader
          v-model="selectedCategory"
          expand-trigger="hover"
          :options="categoryList"
          :props="categoryTreeProps"
          :clearable="true"
          @change="handleChange"
        />
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn primary-btn"
          @click="searchProd"
        >
          {{ $t("coupon.query") }}
        </div>
        <div
          class="default-btn"
          @click="clean"
        >
          {{ $t("product.reset") }}
        </div>
      </el-form-item>
    </el-form>
    <div class="prods-select-body">
      <el-table
        ref="prodTableRef"
        v-loading="dataListLoading"
        :data="dataList"
        header-cell-class-name="table-header"
        row-class-name="table-row"
        height="500"
        style="width: 100%"
        @select="selectChangeHandle"
        @select-all="selectAllHandle"
      >
        <el-table-column
          v-if="isSingle"
          width="50"
          header-align="center"
          align="center"
        >
          <template #default="scope">
            <div>
              <el-radio
                v-model="singleSelectProdId"
                :label="scope.row.prodId"
                @change="getSelectProdRow(scope.row)"
              >
&nbsp;
              </el-radio>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="!isSingle"
          type="selection"
          header-align="center"
          align="center"
          width="50"
        />
        <el-table-column
          prop="prodName"
          header-align="center"
          align="center"
          :label="$t('coupon.commodityName')"
        />
        <el-table-column
          align="center"
          width="140"
          :label="$t('product.pic')"
        >
          <template #default="scope">
            <img-show
              :src="scope.row.pic"
              :img-style="{width:'100px',height:'100px'}"
            />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="totalPage"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
        />
      </div>
    </div>
    <template #footer>
      <div>
        <div
          class="default-btn"
          @click="close"
        >
          {{ $t("coupon.cancel") }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="submitProds()"
        >
          {{ $t("coupon.confirm") }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { treeDataTranslate, idList } from '@/utils'
const props = defineProps({
  isSingle: {
    default: false,
    type: Boolean
  },
  prodType: {
    default: null,
    type: Number
  },
  dataUrl: {
    default: '/platform/search/prod/page',
    type: String
  }
})
const emit = defineEmits(['refreshSelectProds'])

const dataForm = reactive({
  product: ''
})

const categoryTreeProps = reactive({
  value: 'categoryId',
  label: 'categoryName'
})
onActivated(() => {
  getDataList()
})

const prodTableRef = ref(null)
onBeforeUnmount(() => {
  prodTableRef.value?.clearSelection()
})

const singleSelectProdId = ref(0)
let selectProds = []
const visible = ref(false)
const dataListLoading = ref(false)
let dataListSelections = []
// 获取数据列表
const init = (selectProdsPar) => {
  singleSelectProdId.value = 0
  selectProds = selectProdsPar
  visible.value = true
  dataListLoading.value = true
  if (selectProds) {
    selectProds.forEach(row => {
      dataListSelections.push(row)
    })
  }
  getDataList(true)
  getCategoryList()
}

const categoryList = ref([])
const getCategoryList = () => {
  http({
    url: http.adornUrl('/prod/category/listCategory'),
    method: 'get',
    params: http.adornParams({
      maxGrade: 2,
      status: 1
    })
  }).then(({ data }) => {
    categoryList.value = treeDataTranslate(data, 'categoryId', 'parentId')
    // 去除没有3级的类目
    checkLevel(categoryList.value, 2)
  })
}

const checkLevel = (list, level) => {
  for (let i = 0; i < list.length; i++) {
    if (!list[i].children || !list[i].children.length) {
      list.splice(i, 1)
      i--
      continue
    }
    if (--level > 0) {
      checkLevel(list[i].children, level)
    }
    if (!list[i].children.length) {
      list.splice(i, 1)
      i--
    }
  }
}

const prodName = ref(null)
const pageIndex = ref(1)
const pageSize = ref(10)
let categoryId = null
const dataList = ref([])
const totalPage = ref(0)
const getDataList = (init = false) => {
  http({
    url: http.adornUrl(props.dataUrl),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageIndex.value,
          size: pageSize.value,
          prodName: prodName.value,
          keyword: prodName.value,
          categoryId,
          status: 1,
          prodType: props.prodType,
          mustNotProdTypes: 3,
          isActive: 1 // 过滤掉活动商品
        }
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    totalPage.value = data.total
    dataListLoading.value = false

    if (init && selectProds && selectProds.length) {
      nextTick(() => {
        selectProds.forEach(row => {
          const index = dataList.value.findIndex((prodItem) => prodItem.prodId === row.prodId)
          if (index >= 0) {
            prodTableRef.value?.toggleRowSelection(dataList.value[index], true)
          }
        })
      })
    } else if (dataListSelections && dataListSelections.length) {
      nextTick(() => {
        dataListSelections.forEach(row => {
          const index = dataList.value.findIndex((prodItem) => prodItem.prodId === row.prodId)
          prodTableRef.value?.toggleRowSelection(dataList.value[index], true)
        })
      })
    }
  })
}

// 每页数
const sizeChangeHandle = (val) => {
  pageSize.value = val
  pageIndex.value = 1
  getDataList()
}

// 当前页
const currentChangeHandle = (val) => {
  pageIndex.value = val
  getDataList()
}

// 单选商品事件
const getSelectProdRow = (row) => {
  dataListSelections = [row]
}

// 多选点击事件
const selectChangeHandle = (selection) => {
  dataList.value.forEach((tableItem) => {
    const selectedProdIndex = selection.findIndex((selectedProd) => {
      if (!selectedProd) {
        return false
      }
      return selectedProd.prodId === tableItem.prodId
    })
    const dataSelectedProdIndex = dataListSelections.findIndex((dataSelectedProd) => dataSelectedProd.prodId === tableItem.prodId)
    if (selectedProdIndex > -1 && dataSelectedProdIndex === -1) {
      dataListSelections.push(tableItem)
    } else if (selectedProdIndex === -1 && dataSelectedProdIndex > -1) {
      dataListSelections.splice(dataSelectedProdIndex, 1)
    }
  })
}

const selectAllHandle = () => {
  dataList.value.forEach((tableItem) => {
    const selectedProdIndex = dataListSelections.findIndex((selectedProd) => {
      if (!selectedProd) {
        return false
      }
      return selectedProd.prodId === tableItem.prodId
    })
    if (selectedProdIndex === -1) {
      dataListSelections.push(tableItem)
    }
  }
  )
}

/**
 * 获取分类id
 */
const handleChange = (val) => {
  categoryId = val[val.length - 1]
}

/**
 * 根据条件搜索商品
 */
const searchProd = () => {
  pageIndex.value = 1
  getDataList()
}

const selectedCategory = ref([])
/**
 * 清空搜索条件
 */
const clean = () => {
  prodName.value = ''
  categoryId = null
  selectedCategory.value = idList(categoryList.value, categoryId, 'categoryId', 'children').reverse()
}

const close = () => {
  dataListSelections = []
  prodName.value = ''
  categoryId = null
  visible.value = false
}

// 确定事件
const submitProds = () => {
  // 商品单选情况
  if (props.isSingle) {
    dataListSelections.length && emit('refreshSelectProds', dataListSelections[0])
    // 商品多选情况
  } else {
    const prods = []
    dataListSelections.forEach(item => {
      const prodIndex = prods.findIndex((prod) => prod.prodId === item.prodId)
      if (prodIndex === -1) {
        prods.push(
          {
            prodId: item.prodId,
            prodName: item.prodName,
            // 避免多次选择拼接多个resourcesUrl
            pic: checkFileUrl(item.pic),
            prodType: item.prodType,
            oriPrice: item.oriPrice,
            price: item.price,
            brief: item.brief,
            activityPrice: item.activityPrice
          }
        )
      }
    })
    emit('refreshSelectProds', prods)
  }
  dataListSelections = []
  visible.value = false
}

defineExpose({
  init
})

</script>

<style lang="scss" scoped>
.pagination {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}
</style>
